<template>
  <div class="page-container">
    <div class="page-header">
      <h2>MQTT连接管理</h2>
    </div>

    <el-card class="mqtt-card">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="MQTT IN" name="in">
          <div class="table-header">
            <div class="left">
              <el-button type="primary" @click="showAddDialog">
                <el-icon><Plus /></el-icon>
                添加节点
              </el-button>
            </div>
            <div class="right">
              <el-input
                v-model="searchQuery"
                placeholder="搜索..."
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <el-table
            :data="filteredInTopics"
            v-loading="loading"
            border
            style="width: 100%"
          >
            <el-table-column prop="name" label="名称" min-width="120" />
            <el-table-column prop="service" label="服务器" min-width="150" />
            <el-table-column prop="topic" label="主题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="qos" label="QoS" width="100" align="center" />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '活跃' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    :icon="Edit"
                    size="small"
                    @click="handleEdit(scope.row)"
                  />
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    @click="handleDelete(scope.row)"
                  />
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="MQTT OUT" name="out">
          <div class="table-header">
            <div class="left">
              <el-button type="primary" @click="showAddDialog">
                <el-icon><Plus /></el-icon>
                添加节点
              </el-button>
            </div>
            <div class="right">
              <el-input
                v-model="searchQuery"
                placeholder="搜索..."
                style="width: 200px"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <el-table
            :data="filteredOutTopics"
            v-loading="loading"
            border
            style="width: 100%"
          >
            <el-table-column prop="name" label="名称" min-width="120" />
            <el-table-column prop="service" label="服务器" min-width="150" />
            <el-table-column prop="topic" label="主题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="qos" label="QoS" width="100" align="center" />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '活跃' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    :icon="Edit"
                    size="small"
                    @click="handleEdit(scope.row)"
                  />
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    @click="handleDelete(scope.row)"
                  />
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加节点' : '编辑节点'"
      v-model="dialogVisible"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="服务器" prop="service">
          <el-input v-model="form.service" placeholder="请输入服务器地址" />
        </el-form-item>
        <el-form-item label="主题" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入主题" />
        </el-form-item>
        <el-form-item label="QoS" prop="qos">
          <el-select v-model="form.qos" placeholder="请选择QoS">
            <el-option label="0" :value="0" />
            <el-option label="1" :value="1" />
            <el-option label="2" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Search,
  Edit,
  Delete
} from '@element-plus/icons-vue';

const activeTab = ref('in');
const loading = ref(false);
const searchQuery = ref('');
const inTopics = ref([]);
const outTopics = ref([]);
const dialogVisible = ref(false);
const dialogType = ref('add');
const formRef = ref(null);

const form = ref({
  name: '',
  service: '',
  topic: '',
  qos: 0,
  status: true
});

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  service: [{ required: true, message: '请输入服务器地址', trigger: 'blur' }],
  topic: [{ required: true, message: '请输入主题', trigger: 'blur' }],
  qos: [{ required: true, message: '请选择QoS', trigger: 'change' }]
};

// 过滤后的主题列表
const filteredInTopics = computed(() => {
  if (!searchQuery.value) return inTopics.value;
  const query = searchQuery.value.toLowerCase();
  return inTopics.value.filter(topic => 
    topic.name.toLowerCase().includes(query) ||
    topic.service.toLowerCase().includes(query) ||
    topic.topic.toLowerCase().includes(query)
  );
});

const filteredOutTopics = computed(() => {
  if (!searchQuery.value) return outTopics.value;
  const query = searchQuery.value.toLowerCase();
  return outTopics.value.filter(topic => 
    topic.name.toLowerCase().includes(query) ||
    topic.service.toLowerCase().includes(query) ||
    topic.topic.toLowerCase().includes(query)
  );
});

const fetchTopics = async () => {
  loading.value = true;
  try {
    const response = await fetch('https://penglink.pcwxcn.top/api/mqtt/topics', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    const result = await response.json();
    if (result.code === 200) {
      // 根据类型分类
      inTopics.value = result.data.filter(topic => topic.type === 'in');
      outTopics.value = result.data.filter(topic => topic.type === 'out');
    }
  } catch (error) {
    console.error('获取通道列表错误:', error);
    ElMessage.error('获取通道列表失败');
  } finally {
    loading.value = false;
  }
};

const showAddDialog = () => {
  dialogType.value = 'add';
  form.value = {
    name: '',
    service: '',
    topic: '',
    qos: 0,
    status: true,
    type: activeTab.value
  };
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogType.value = 'edit';
  form.value = { ...row };
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' 
          ? 'https://penglink.pcwxcn.top/api/mqtt/topics'
          : 'https://penglink.pcwxcn.top/api/mqtt/topic/update';
        
        const response = await fetch(url, {
          method: dialogType.value === 'add' ? 'POST' : 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify(form.value)
        });

        const result = await response.json();
        if (result.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
          dialogVisible.value = false;
          fetchTopics();
        } else {
          throw new Error(result.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'));
        }
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error(error.message || '操作失败');
      }
    }
  });
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除通道 ${row.name} 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await fetch(`https://penglink.pcwxcn.top/api/mqtt/topics?id=${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    const result = await response.json();
    if (result.code === 200) {
      ElMessage.success('删除成功');
      fetchTopics();
    } else {
      throw new Error(result.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(error.message || '删除失败');
    }
  }
};

// 初始化
fetchTopics();
</script>

<style scoped>
.page-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #1f2f3d;
}

.mqtt-card {
  margin: 16px;
  border-radius: 4px;
}

.mqtt-card :deep(.el-card__body) {
  padding: 20px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header .left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.table-header .right {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-table) {
  margin-top: 16px;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
